package com.example.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.entity.*;
import com.example.admin.mapper.SysPermissionMapper;
import com.example.admin.service.ISysPermissionService;
import com.example.admin.service.ISysRolePermissionService;
import com.example.admin.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资源权限信息表 服务实现类
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@Service("sysPermissionService")
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
        implements ISysPermissionService {

    @Autowired
    private ISysRolePermissionService rpService;

    @Autowired
    private ISysRoleService roleService;

    @Override
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public boolean deleteParmission(SysPermission permission) {
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_id", permission.getId());
        if (rpService.remove(queryWrapper)) {
            if (!permission.deleteById()) {
                throw new RuntimeException();
            }
        } else {
            throw new RuntimeException();
        }
        return true;
    }

    @Override
    public List<SysPermission> getUserList(SysUser sysUser) {
        List<SysRole> list = roleService.getRoleList(sysUser.getId());
        List<SysPermission> result = new ArrayList<>();
        for (SysRole sysRole : list) {
            if (sysRole.getPermissions() != null && sysRole.getPermissions().size() > 0) {
                result.addAll(sysRole.getPermissions());
            }
        }
        return result;
    }

    @Override
    public List<SysPermission> getRoleList(Integer roleId) {
        SysRole sysRole = roleService.getRole(roleId);
        return sysRole.getPermissions();
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public boolean insertPermission(SysPermission permission) {
        if (permission.insert()) {
            if (permission.getId() != null) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(1);
                rolePermission.setPermissionId(permission.getId());
                if (!rolePermission.insert()) {
                    throw new RuntimeException();
                }
            }
        }
        return true;
    }

}
